//
//  RHBatchS40KVPPConfigVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/2/21.
//

#import "RHBatchS40KVPPConfigVC.h"
#import "SYChartTool.h"
#import "ZYSwitch.h"
#import "SettingOptionController.h"
#import "PasswordVerifyController.h"
#import "RHTools.h"
#import "KWTMGRNSettingDateCell.h"
#import "RHUserGroupDateSettingCell.h"
#import "KWTMGRNSettingSelectCell.h"
#import "KWTMGRNSettingSwitchCell.h"
#import "KWTMGRNSettingChgTimeCell.h"
#import "KWTMGRNSettingEditTimeVC.h"
#import "WSDatePickerView.h"
#import "NetworkAgent.h"
#import "KWTPlantGroupModel.h"
#import "RHUserGroupModel.h"

@interface RHBatchS40KVPPConfigVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *paraSectionArr;//每组的参数

@property (nonatomic ,assign) NSInteger paraIndex;//参数下标

@property (nonatomic, strong) NSArray *syncArr;//要同步的设备   deviceId

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic,assign) BOOL paraSetValid;//时间段参数设置使能

@end

@implementation RHBatchS40KVPPConfigVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"批量策略配置".rh_localized;
    self.paraSectionArr = [NSMutableArray array];
    [self setupUI];
    [self loadParamData];
}


- (void)setupUI{
    kWeakSelf;
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_mgrn_chg"];
    NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:arr];
    //去掉系统时间校准
    [mtbArr removeObjectAtIndex:0];
    self.dataArr = [NSArray yy_modelArrayWithClass:[KWTMGRNSettingModel class] json:mtbArr.copy];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[KWTMGRNSettingDateCell class] forCellReuseIdentifier:@"KWTMGRNSettingDateCell"];
    [_tableView registerClass:[RHUserGroupDateSettingCell class] forCellReuseIdentifier:@"RHUserGroupDateSettingCell"];
    [_tableView registerClass:[KWTMGRNSettingSelectCell class] forCellReuseIdentifier:@"KWTMGRNSettingSelectCell"];
    [_tableView registerClass:[KWTMGRNSettingSwitchCell class] forCellReuseIdentifier:@"KWTMGRNSettingSwitchCell"];
    [_tableView registerClass:[KWTMGRNSettingChgTimeCell class] forCellReuseIdentifier:@"KWTMGRNSettingChgTimeCell"];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
     
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];

    
    
}

#pragma mark ---- 获取保存的配置
-(void)loadParamData
{
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{@"configType":@(3)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            NSDictionary *dataDic = request.responseJSONObject[@"data"];
            if (dataDic[@"strategy"]) {
                NSDictionary *dic = [dataDic[@"strategy"] jsonStringToDictionary];
                NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                //工作模式强制设为削峰填谷
                [mtbDic setObject:@"1" forKey:@"Inv3_AdvaMode"];
                [mtbDic setObject:@"1" forKey:@"Inv3_TOUEn"];
                
                if(dic[@"protocolBody"]){
                    NSArray *dicArr = dic[@"protocolBody"][@"commandParamList"];
                    [dicArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull paraDic, NSUInteger idx, BOOL * _Nonnull stop) {
                        [mtbDic setObject:ValidNullData(paraDic[@"value"]) forKey:ValidNullData(paraDic[@"paramName"])];
                    }];
                    [self readDefult:mtbDic];
                    [self.tableView reloadData];
                }
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
   
}

//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    [self.dataArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [model readDefult:dic];
        
        //时间校准显示当前时间 ,在分组设置时是读取不到的参数的
        [model.rows enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull row_model, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([row_model.type isEqualToString:@"date"]) {
                row_model.content = [NSDate dateStringWithTimeInterval:[[NSDate date]timeIntervalSince1970] formatter:@"yyyy/MM/dd HH:mm:ss"];
            }
            
            
            if([row_model.type isEqualToString:@"time"])//时间段设置
            {
               
            }
        }];
        
        
        
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        return 20;
    }
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
        headV.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 10)];
        bgView.backgroundColor = UIColor.whiteColor;
        bgView.layer.cornerRadius = 8;
        bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
        bgView.layer.masksToBounds = YES;
        [headV addSubview:bgView];
        return headV;
    }
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    headerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
    KWTMGRNSettingModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 45)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.layer.masksToBounds = YES;
    [headerView addSubview:bgView];
    
    QMUILabel *titleLab = [QMUILabel labelWithText:sectionModel.sectionTitle.rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(1);
    }];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    kWeakSelf;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    footerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
//    KWTMGRNSettingModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    bgView.layer.masksToBounds = YES;
    [footerView addSubview:bgView];
    
    
    return footerView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    KWTMGRNSettingModel *sectionModel = self.dataArr[section];
    return sectionModel.rows.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KWTMGRNSettingModel *sectionModel = self.dataArr[indexPath.section];
    KWTMGRNSettingModel *rowModel = sectionModel.rows[indexPath.row];
    if ([rowModel.type isEqualToString:@"date"]) {//系统时间校准
        kWeakSelf;
        if (self.userGroupModel) {//用户分组进去
            RHUserGroupDateSettingCell *userGroupDateCell = [tableView dequeueReusableCellWithIdentifier:@"RHUserGroupDateSettingCell"];
            userGroupDateCell.setAction = ^() {
                [weakSelf userGroupSetDate];
            };
            userGroupDateCell.selectionStyle = UITableViewCellSelectionStyleNone;
            return userGroupDateCell;
        }
        
        KWTMGRNSettingDateCell *dateCell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingDateCell"];
        dateCell.model = rowModel;
      
        //时间选择
        dateCell.selectAction = ^(KWTMGRNSettingModel * _Nonnull model) {
            [weakSelf dateAction:model];
        };
        //时间设置
        dateCell.setAction = ^(KWTMGRNSettingModel * _Nonnull model) {
            [weakSelf setDateAction:model];
        };
        //时间读取
        dateCell.readAction = ^(KWTMGRNSettingModel * _Nonnull model) {
//            [weakSelf readParamData];
        };
        [dateCell hideRefreshButton];
        dateCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dateCell;
    }
    if ([rowModel.type isEqualToString:@"select"]) {//工作模式
        KWTMGRNSettingSelectCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingSelectCell"];
        settingCell.model = rowModel;
        kWeakSelf;
        settingCell.selectAction = ^(KWTMGRNSettingModel * _Nonnull model) {
            [weakSelf selectAction:model];
        };
        settingCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return settingCell;
    }else  if ([rowModel.type isEqualToString:@"switch"]) {//充电使能
        KWTMGRNSettingSwitchCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingSwitchCell"];
        settingCell.model = rowModel;
//        [settingCell showLine: !(indexPath.row == sectionModel.rows.count - 1)];
        return settingCell;
    }else  if ([rowModel.type isEqualToString:@"time"]) {//充放电时段设置
        KWTMGRNSettingChgTimeCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingChgTimeCell"];
        rowModel.rowTitle = [NSString stringWithFormat:@"%@ %ld",@"时段".rh_localized,indexPath.row+1];
        settingCell.model = rowModel;
        kWeakSelf;
        settingCell.selectAction = ^(KWTMGRNSettingModel * _Nonnull model) {
            [weakSelf editChargeDischargeInfo:model index:indexPath.row+1];
        };
        settingCell.commitAction = ^(KWTMGRNSettingModel * _Nonnull model) {
//            [weakSelf checkParaEnableStatus];
            [weakSelf commitAction];
        };
        settingCell.readAction = ^(KWTMGRNSettingModel * _Nonnull model) {
//            [weakSelf readParamData];
        };
        return settingCell;
    }
    return [UITableViewCell new];
}

#pragma mark -------- 充放电时间段选择
-(void)editChargeDischargeInfo:(KWTMGRNSettingModel*)model index:(NSInteger)index
{
    kWeakSelf;
    KWTMGRNSettingEditTimeVC *editVC = [[KWTMGRNSettingEditTimeVC alloc]init];
    editVC.index = index;
    editVC.model = model;
    editVC.sureBlock = ^{
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark -------- 选择时间
- (void)dateAction:(KWTMGRNSettingModel *)settingModel  {
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------ 选择
-(void)selectAction:(KWTMGRNSettingModel*)model
{
    kWeakSelf;
    SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.selectList];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
    vc.curTextValue = [model.content integerValue];
   
    vc.selectBlock = ^(NSInteger index) {
        DevSettingOptionModel *select_model = model.selectList[index];
        model.enumText = select_model.text;//存要显示的内容
        model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];//存下标
        [weakSelf.tableView reloadData];
    };
}




#pragma mark -------- 提交参数前
-(void)commitAction
{
   
    if ([self createSectionSetPara]) {
        [self devParamsSetFromNetwork];
    }
}

//把设置指令分组下发   没有值的参数不下发
-(BOOL)createSectionSetPara
{
    self.paraIndex = 0;
    [self.paraSectionArr removeAllObjects];
    //参数下发时带上 高级模式为放电优先  TOU时间使能打开 这两个参数
    NSDictionary *modeDic = @{
        @"paramName": @"Inv3_AdvaMode",
        @"regAddr" : @(1067),
        @"offset" : @(0),
        @"num" : @(16),
        @"dataType" : @"int",
        @"value" : @"1"

    };

    NSDictionary *touDic = @{
        @"paramName": @"Inv3_TOUEn",
        @"regAddr" : @(1069),
        @"offset" : @(4),
        @"num" : @(1),
        @"dataType" : @"int",
        @"value" : @"1"

    };
    [self.paraSectionArr addObject:modeDic];
    [self.paraSectionArr addObject:touDic];
    
    __block BOOL isCheckOK = YES;//校验是否通过
    [self.dataArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        //上一时间段的结束时间,如果有就比较(当前时间段的开始时间要大于上一段的结束时间)
        __block NSString* lastEndTime;
        __block NSInteger lastEndTimeIndex = 0;
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            if (!isCheckOK) {//校验不通过
                *stop = !isCheckOK;
                return;
            }
            
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                [self.paraSectionArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
                NSMutableArray *itemParaArr = [NSMutableArray array];
                
                __block NSString *t_value = @"";//充电使能的值
                __block NSString *startTime;//每段的开始时间
                __block NSString *endTime;  //每段的结束时间
                [rowModel.items enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if (itemModel.content.length == 0) {
                        //如果Inv3_T%zdEn(充电使能)有值,那么Inv3_Gen%ldEn(放电使能)也要有值
                        if ([itemModel.key containsString:@"Inv3_Gen"]) {
                            if (t_value.length == 0) {
                                return;
                            }
                        }else{
                            return;
                        }
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullData(itemModel.content) forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    //先保存充电使能的值
                    NSString *t_key = [NSString stringWithFormat:@"Inv3_T%zdEn",rowIdx+1];
                    if ([itemModel.key isEqualToString:t_key]) {
                        t_value = itemModel.content;
                    }
                    //Inv3_Gen1En(卖电使能) 要跟 Inv3_T1En(充电使能) 相反
                    if ([itemModel.key containsString:@"Inv3_Gen"]) {
                        [itemDic setObject:[NSString stringWithFormat:@"%d",![t_value boolValue]] forKey:@"value"];
                        
                        //如果为待机 充电使能额外增加枚举值2做为判断
                        if ([t_value integerValue]==2) {
                            [itemDic setObject:@"0" forKey:@"value"];
                            __block NSMutableDictionary *t_En_dic;
                            //找到使能的这个参数字典
                            [self.paraSectionArr enumerateObjectsUsingBlock:^(NSMutableDictionary*  _Nonnull paraDic, NSUInteger idx, BOOL * _Nonnull stop) {
                                if ([paraDic[@"paramName"] isEqualToString:t_key]) {
                                    t_En_dic = paraDic;
                                }
                            }];
                            if (t_En_dic) {
                                [t_En_dic setObject:@"0" forKey:@"value"];
                            }
                        }
                    }
                    
                    //时间  去掉@":"  01:30 --> 0130
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    
                    //判断结束时间是否大于开始时间
                    NSString *startTime_key = [NSString stringWithFormat:@"Inv3_TS%zd",rowIdx+1];
                    NSString *endTime_key   = [NSString stringWithFormat:@"Inv3_TD%zd",rowIdx+1];
                    if ([itemModel.key isEqualToString:startTime_key]&&itemModel.content.length>0) {
                        //开始时间
                        startTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        KWTMGRNSettingModel  *endTimeModel = [rowModel.items safeObjectAtIndex:idx+1];
                        if ([endTimeModel.key isEqualToString:endTime_key]&&endTimeModel.content.length>0) {
                            //结束时间
                            endTime = [endTimeModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        }
                        
                        //判断当前开始时间是否大于上一段结束时间 如果两个是00:00的话不判断
                        BOOL bothZero = ([startTime integerValue]==0)&&([endTime integerValue]==0);
                        if (startTime.length>0 && lastEndTime.length>0) {
                            if (([startTime integerValue]<[lastEndTime integerValue])&&(!bothZero)) {
                                [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld开始时间必须大于或等于时段%ld结束时间".rh_localized,rowIdx+1,lastEndTimeIndex+1]];
                                isCheckOK = NO;
                                return;
                            }
                        }
                    }
                    if ([itemModel.key isEqualToString:endTime_key]&&itemModel.content.length>0) {
                        endTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                       
                        //上一段时间是00:00 - 00:00的话不比较
                        if ([endTime integerValue] != 0) {
                            lastEndTime = endTime;//保存上一时间段的结束时间(有时的情况下)
                            lastEndTimeIndex = rowIdx;
                        }
                    }
                    
                    [self.paraSectionArr addObject:itemDic];
                }];
                
                if (itemParaArr.count>0) {
                    [self.paraSectionArr addObject:itemParaArr];
                }
                
                if (startTime || endTime) {//如果一组里有一个时间填了,就比较,都没填的话不比较
                    if (([endTime integerValue] <= [startTime integerValue])&&([startTime integerValue]!=0)) {//两个都是00:00的就不比较
                        isCheckOK = NO;
                        [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld结束时间必须大于开始时间".rh_localized,rowIdx+1]];
                    }
                }
            }
            
        }];
      
        
    }];
    if (self.paraSectionArr.count <= 2) {
        isCheckOK = NO;
    }
    //校验不通过不提交
    if (isCheckOK == NO) {
        return NO;
    }
    
    return YES;
}

//把设置指令分组下发   没有值的参数传0
-(void)createSectionReadPara
{
    self.paraIndex = 0;
    [self.paraSectionArr removeAllObjects];
    [self.dataArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *paraListArr = [NSMutableArray array];
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                NSString *value = rowModel.content;
                if (rowModel.content.length == 0) {
                    value = @"0";
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:value forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                [paraListArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
                NSMutableArray *itemParaArr = [NSMutableArray array];
                [rowModel.items enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *value = itemModel.content;
                    if (itemModel.content.length == 0) {
                        value = @"0";
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:value forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    [itemParaArr addObject:itemDic];
                }];
                if (itemParaArr.count>0) {
                    [self.paraSectionArr addObject:itemParaArr];
                }
                
            }
            
        }];
        if (paraListArr.count>0) {
            [self.paraSectionArr addObject:paraListArr];
        }
        
    }];
    
    
}


#pragma mark ------ 保存参数配置
- (void)devParamsSetFromNetwork{
    

    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:self.paraSectionArr];

    if (paraListArr.count == 0) {
        return;
    }
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    NSDictionary *para = @{@"protocolHead":headContent,
                           @"protocolBody":bodyDic};
    NSString *paraStr = [para yy_modelToJSONString];
    NSDictionary *requestPara = @{
        @"configType":@"3",//1.强制充放电 2.233  3.S40K  4.solark
        @"strategy":paraStr
    };
    
    [QMUITips showLoading:@"保存中...".rh_localized inView:kApplication.keyWindow];
    
    [BaseModel startWithCompletionAPIKey:H_savePlantGroupForceConfig argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"保存完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    
    }];
}

#pragma mark ------  用户分组时间校准,只调接口就行,后台会自根据分组里的用户的电站进行相应时区时间校准
-(void)userGroupSetDate
{
    [QMUITips showLoadingInView:kAppWindow];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_userGroupSystemTimeSet_2,self.userGroupModel.groupId];
    [BaseModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark ------ 时间校准 密码校验
-(void)setDateAction:(KWTMGRNSettingModel*)model
{
    if (model.content.length == 0) {
        return;
    }
    //    PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
    //    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    //
    //    kWeakSelf;
    //    vc.callBackBlock = ^(NSString * _Nonnull password) {
    //                NSDictionary *dic = [RHTools getAccountInfo];
    //                if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
    //                    [weakSelf systemTimeVerity:model];
    //                }else{
    //                    [QMUITips showInfo:@"密码错误".rh_localized];
    //                }
    //    };
    [self vppSetSystemTime:model];
   
}

#pragma mark ------分组设置 时间校准 提交参数
-(void)vppSetSystemTime:(KWTMGRNSettingModel*)model
{
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    [requestPara setObject:@(self.groupModel.groupId) forKey:@"groupId"];
    if (self.userGroupModel) {
        [requestPara setObject:@(self.userGroupModel.groupId) forKey:@"groupId"];
    }
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    if (model.content.length>0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
        formatter.timeZone = [NSTimeZone localTimeZone];
        NSDate *date = [formatter dateFromString:model.content];
        
        [self processTimeParams:paraListArr date:date];
    }

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];
    NSString *url = H_groupVppSetSystemTime;
    if (self.userGroupModel) {
        url = H_userGroupSystemTimeSet;
    }
    [BaseModel startWithCompletionAPIKey:url argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"设置完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.finishBlock) {
                    self.finishBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    
    }];
}

#pragma mark ------- 处理麦格瑞能时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Inv3_RTCYear",@"Inv3_RTCMonth",@"Inv3_RTCDay",@"Inv3_RTCHour",@"Inv3_RTCMinute",@"Inv3_RTCSecond"];
    NSArray *value = @[@(date.year%100),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(1160+idx) forKey:@"regAddr"];//1160-1165
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}




-(UIView*)footerView{
    kWeakSelf;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 80)];
    
    QMUIButton *commitBtn = [[QMUIButton alloc]init];
    [commitBtn setTitle:@"保存".rh_localized forState:UIControlStateNormal];
    [commitBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [commitBtn setCornerRadius:8];
    [commitBtn setBackgroundColor:CMainColorGreen];
    [footer addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.offset(45);
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
//    QMUIButton *readBtn = [[QMUIButton alloc]init];
//    [readBtn setTitle:@"读取".rh_localized forState:UIControlStateNormal];
//    [readBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
//    [readBtn setCornerRadius:8];
//    [readBtn setBackgroundColor:CMainColorGreen];
//    [footer addSubview:readBtn];
//    [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(commitBtn.mas_right).offset(15);
//        make.right.mas_offset(-15);
//        make.height.width.equalTo(commitBtn);
//        make.centerY.equalTo(commitBtn);
//    }];
    
    [[commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf commitAction];
    }];
    
//    [[readBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
//        [weakSelf createSectionReadPara];
//        [weakSelf.hud hideAnimated:NO];
//        [weakSelf showHud];
//        [weakSelf readParamData];
//    }];
    return footer;
}


-(void)showHud{
    if (self.navigationController.view==nil) {
        return;
    }
    _hud = [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
    _hud.mode = MBProgressHUDModeIndeterminate;
    //不使用蒙版,使用背景颜色
    _hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.bezelView.backgroundColor = kColorRGBA(0, 0, 0,  0.8);
    _hud.bezelView.layer.cornerRadius = 8;
    _hud.bezelView.layer.masksToBounds = YES;
    //图片和文字的颜色
    _hud.contentColor = [UIColor whiteColor];
    _hud.removeFromSuperViewOnHide = YES;
    _hud.label.text = @"";
    // Configure the button.
    [_hud.button setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    [_hud.button addTarget:self action:@selector(cancelWork:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)cancelWork:(UIButton*)button
{
    [[NetworkAgent sharedAgent] cancelAllRequests];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self.hud hideAnimated:YES];
   
}


@end
